package com.homelink.android.explorerup.component;

import java.io.File;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;

public class PathAdapter {
	private Context mContext;
	private String mPath;
	ViewGroup mParentView;
	private View.OnClickListener mListener;

	public PathAdapter(ViewGroup parentView, Context ctx) {
		mParentView = parentView;
		mContext = ctx;
	}

	public void setListener(View.OnClickListener listener) {
		mListener = listener;
	}

	// scroll view need to scroll to end
	public void setPath(String path) {
		if (path == null) {
			return;
		}
		mPath = path;
		StringBuilder sb = new StringBuilder(path);
		int startIndex = 1;
		mParentView.removeAllViews();
		int lastIndex = sb.length() - 1;
		View v = createView(" / ");
		v.setTag("/");
		mParentView.addView(v);
		String tmp = null;
		for (int i = 1; i < sb.length(); i++) {
			if (sb.charAt(i) == File.separatorChar) {
				tmp = sb.substring(startIndex, i);
				v = createView(tmp);
				v.setTag(sb.subSequence(0, i));
				mParentView.addView(v);
				startIndex = i + 1;
			} else if (i == lastIndex) {
				tmp = sb.substring(startIndex);
				v = createView(tmp);
				v.setTag(mPath);
				mParentView.addView(v);
			}
		}
	}

	public String getPath() {
		return mPath;
	}

	private View createView(String txt) {
		Button btn = new Button(mContext);
		btn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.FILL_PARENT));
		btn.setText(txt);
		btn.setTextSize(30);
		btn.setOnClickListener(mListener);
		return btn;
	}
}
